package cn.wq3stone.util;

import java.sql.*;
import java.util.ResourceBundle;

/**
 * @ClassName DBUtil.java
 * @Description
 * @Author cn.wq3stone
 * @Date 2023/4/24 20:28
 */
public class DBUtil {
    private  static ResourceBundle bundle = ResourceBundle.getBundle("resources/db");
    private static String driver = bundle.getString("driver");
    private static String url = bundle.getString("url");
    private static String user = bundle.getString("username");
    private static String password = bundle.getString("password");

    // DBUtil类加载时注册驱动
    static {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    // 为了防止创建对象，将构造方法私有化
    private DBUtil(){}

    /**
     * 没有使用数据库连接池，直接创建连接对象
     * @return 连接对象
     */
    public static Connection getConnection() throws SQLException {
        Connection connection = DriverManager.getConnection(url,user,password);
        return connection;
    }

    /**
     * 关闭连接对象
     * @param conn
     * @param stmt
     * @param rs 结果集
     */
    public static void close(Connection conn, Statement stmt, ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
